const appid = 'wx402d332ba0f06174'
const appsecret = '32a60a96da0beb144e29c64d3687128c'
const request = require('request')
const node_cache = require('node-cache')
const accessCache =  new node_cache({stdTTL:  600 ,checkperiod:120});
function getAccessToken(callback){
	 const token = accessCache.get('access_token')
	 console.log(token,'toto')
	 if (token == undefined){
	 request({
		 	url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appid + '&secret=' + appsecret,
		 	method: "GET",
		 	timeout: 10000,
		 },function(error, response, body){
		 	console.log(body,'bobo',JSON.parse(body).access_token)
			if (body.length > 30){
				const parsed = JSON.parse(body)
				accessCache.set('access_token',parsed.access_token,parsed.expires_in,function(err,success){
					callback(parsed.access_token)
				})
			}
			else{
				callback('')
			}

	})	 	
	 }
	 else{
	 	callback(token)
	 }

}

// expire , book , cancel, reminder , type 0 , book , 1 cancel , 2 reminder , 3 expire
module.exports.sendNotification = function sendNotification(openid,formID,type,appointment,callback){
	var data = {}
	if (type == 0){ // book
		data = {
			'touser' : openid,
			'template_id' : 'CCdjC3hQ9hzIyXhVIH_mVxxogunfXnGSaHkzAY9yABk',
			'page' : 'pages/mybooking/mybooking?id=' + appointment._id,
			'form_id' : formID,
			'data':{
				"keyword1":{
					"value": appointment.store.name + '  (' + appointment.store.address + ')'
				},
				"keyword2":{
					"value": '潮剪理发',
				},
				"keyword3":{
					"value": appointment.stylist.nickName
				}
			},
		"emphasis_keyword":''
		}
	}
	else if (type == 1){
		data = { // cancel
			'touser' : openid,
			'template_id' : 'CCdjC3hQ9hzIyXhVIH_mVxxogunfXnGSaHkzAY9yABk',
			'page' : 'mybooking?id=' + appointment._id,
			'form_id' : formID,
			'data':{
				"keyword1":{
					"value": formatDate(new Date(appointment.day))
				},
				"keyword2":{
					"value": appointment.store.name + '  (' + appointment.store.address + ')',
				},
				"keyword3":{
					"value": appointment.stylist.nickName
				}
			},
		"emphasis_keyword":''
		}
	}
	else if (type == 2){ // reminder
		data = {
			'touser' : openid,
			'template_id' : 'XmgSeYQQi9r86opW5RFOqrgaPdO-uH4GxM7Nu-Fg3XA',
			'page' : 'mybooking?id=' + appointment._id,
			'form_id' : formID,
			'data':{
				"keyword1":{
					"value": appointment.store.name + '  (' + appointment.store.address + ')'
				},
				"keyword2":{
					"value": formatDate(new Date(appointment.day)),
				},
				"keyword3":{
					"value": appointment.stylist.nickName
				},
				"keyword4":{
					"value": '潮剪理发'
				}
			},
		"emphasis_keyword":''
		}
	}
	else if (type == 3){ // expire
		data = {
			'touser' : openid,
			'template_id' : 'CCdjC3hQ9hzIyXhVIH_mVxxogunfXnGSaHkzAY9yABk',
			'page' : 'mybooking?id=' + appointment._id,
			'form_id' : formID,
			'data':{
				"keyword1":{
					"value": formatDate(new Date(appointment.day))
				},
				"keyword2":{
					"value": appointment.store.name + '  (' + appointment.store.address + ')',
				},
				"keyword3":{
					"value": '潮剪理发'
				}
			},
		"emphasis_keyword":''
		}
	}

		getAccessToken(function(token){
			console.log(data,token,'totot')
			request({
				 	url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + token,
				 	method: "POST",
				 	timeout: 10000,
				 	body: JSON.stringify(data),
				      header: {
				        'content-type': 'application/json' // 默认值
				      }
				 },function(error, response, body){
					console.log(body,'aaja',error)
					callback(error,response,body)
			})
		})


}


function formatDate(date){
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
}


function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}